package com.jt.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.jt.pojo.Cart;
import com.jt.pojo.Order;
import com.jt.pojo.User;
import com.jt.service.DubboCartService;
import com.jt.service.DubboOrderService;
import com.jt.vo.SysResult;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/order")
public class OrderController {

    @Reference(check=false)
    private DubboCartService cartService;
    @Reference(check = false)
    private DubboOrderService orderService;

    /**
     * 跳转到页面:/order/create.html
     * 业务:根据userId,查询记录,再页面中显示购物车信息
     */
        @RequestMapping("/create")
        public String create(HttpServletRequest request, Model model){

            User user = (User) request.getAttribute("JT_USER");
            Long userId = user.getId();
            List<Cart> cartList = cartService.findCartListByUserId(userId);
            model.addAttribute("carts", cartList);
            return "order-cart";
        }

    /**
     * 提交订单
     * url:/order/submit
     *参数:form表单提交
     * 返回值:SysResult对象
     */
    @RequestMapping("/submit")
    @ResponseBody
    public SysResult saveOrder(Order order,HttpServletRequest request){

        User user = (User)request.getAttribute("JT_USER");
        Long userId = user.getId();
        order.setUserId(userId);
        String orderId=orderService.saveOrder(order);
        if (StringUtils.isEmpty(orderId)){
            return SysResult.fail();
        }
        return SysResult.success();
    }

    //提交
    /**
     * url:order/success.html?id=?
     */
    @RequestMapping("/success")
    public String findOrderById(String id,Model model){
        Order order=orderService.findOrderById(id);
        model.addAttribute("order", order);
        return "success";
    }
}
